//
//  KQViewController.swift
//  mggz
//
//  Created by Apple on 2018/4/19.
//  Copyright © 2018年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import RxCocoa
import RxSwift


class KQViewController: UIViewController {
    var month:String?
    
    @IBOutlet weak var totalWorkers: UILabel!
    @IBOutlet weak var totalDays: UILabel!
    @IBOutlet weak var totalWork: UILabel!
    @IBOutlet weak var daitotalwork: UILabel!
    @IBOutlet weak var monthlabel: UILabel!
    
    @IBOutlet weak var dwycTxt: UILabel!
    @IBOutlet weak var chidao: UILabel!
    @IBOutlet weak var wkaoqing: UILabel!
    @IBOutlet weak var totalview: UIView!
    @IBOutlet weak var card1: UIView!
    @IBOutlet weak var card2: UIView!
    @IBOutlet weak var card3: UIView!
    
    var card1count,card2count,card3count:Int?
    
    var dateformat:DateFormatter?
    
    var emptyview:EmptyView?
    
    
    lazy var tapClick:UITapGestureRecognizer = {
        var click = UITapGestureRecognizer(target: self, action: #selector(click(_:)))
        click.numberOfTapsRequired = 1
        click.numberOfTouchesRequired = 1
        return click
    }()
    
    var datePicker:PGDatePicker?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let dateFormat = DateFormatter()
        dateFormat.dateFormat = "YYYY-MM"
        self.month = "\(dateFormat.string(from: Date()))-01"
        self.view.backgroundColor = UIColor.LightGreyBG
        
        self.dateformat = DateFormatter()
        dateformat?.dateFormat = "YYYY年MM月"
        print("--->\(dateformat?.string(from: Date()))")
        monthlabel.text = dateformat?.string(from: Date())
        card1.shadowEnable = true
        card2.shadowEnable = true
        card3.shadowEnable = true

        getTongjiTotal()
        
        datePicker = PGDatePicker()
        datePicker?.datePickerMode = .yearAndMonth
        datePicker?.maximumDate = NSDate.setYear(2022)
        datePicker?.minimumDate = NSDate.setYear(2010)
        datePicker?.delegate = self
        
        self.monthlabel.isUserInteractionEnabled = true
        self.monthlabel.addGestureRecognizer(self.tapClick)
        self.monthlabel.tag = 0
        
        card1.isUserInteractionEnabled = true
        card1.tag = 1
        card2.isUserInteractionEnabled = true
        card2.tag = 2
        card3.isUserInteractionEnabled = true
        card3.tag = 3
        self.card1.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(click(_:))))
        self.card2.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(click(_:))))
        self.card3.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(click(_:))))
    }
    
    
    @objc func click(_ sender:UIGestureRecognizer){
        print(sender.view?.tag)
        if sender.view?.tag == 0{
            let datePickerManager = PGDatePickManager()
            datePickerManager.isShadeBackgroud = true
            datePickerManager.style = .style3
            let datePicker = datePickerManager.datePicker!
            datePicker.delegate = self
            datePicker.datePickerType = .type1
            datePicker.datePickerMode = .yearAndMonth
            self.present(datePickerManager, animated: false, completion: nil)
        }else if sender.view?.tag == 1{
            let dwVc = LCDingWeiController(nibName: "LCDingWeiController", bundle: nil)
            dwVc.month = self.month
            dwVc.monthStr = self.monthlabel.text ?? ""
            dwVc.number = self.card1count
            self.navigationController?.pushViewController(dwVc, animated: true)
        }else if sender.view?.tag == 2{
            let cdVc = LCChiDaoController(nibName: "LCChiDaoController", bundle: nil)
            cdVc.month = self.month
            cdVc.monthStr = self.monthlabel.text ?? ""
            cdVc.number = self.card2count!
            self.navigationController?.pushViewController(cdVc, animated: true)
        }else if sender.view?.tag == 3{
            let wkqVc = WKQcontroller(nibName: "WKQcontroller", bundle: nil)
            wkqVc.month = self.month
            wkqVc.number = self.card3count
            wkqVc.monthStr = self.monthlabel.text ?? ""
            self.navigationController?.pushViewController(wkqVc, animated: true)
        }
    }
    
    func getTongjiTotal(){
        QWTextWithStatusHud("正在载入数据...", target: self.view)
        var params:[String:Any]=["constructionProjectID":ProjectId as! String]
        MNetHttp.sharedInstance.postSingle(API_CALL_METHOD, method: .KQTotal, params: &params, type: KaoQingTotal.self, success: { (bean,_) in
            print("\((bean as! KaoQingTotal).Result?.TotalDays)")
            //QWHudDiss(self.view)
            let kaoqingtotal = bean as! KaoQingTotal
            if kaoqingtotal.Result?.WorkDayType == 0||kaoqingtotal.Result?.WorkDayType == 1{
                self.totalWork.text = "总工数：\((kaoqingtotal.Result?.TotalWorkDays)!)工"
                self.daitotalwork.text = "未付工数：\((kaoqingtotal.Result?.TotalNotPayedWorkDays)!)工"
            }else{
                self.totalWork.text = "总工数：\((kaoqingtotal.Result?.TotalWorkHours)!)时"
                self.daitotalwork.text = "未付工数：\((kaoqingtotal.Result?.TotalNotPayedWorkHours)!)时"
            }
            self.totalDays.text = "开工天数：\((kaoqingtotal.Result?.TotalDays)!)天"
            self.totalWorkers.text = "考勤人数：\((kaoqingtotal.Result?.TotalWorkers)!)人"
            self.getTongJiDetail()
        }) { (error) in
            QWHudDiss(self.view)
            switch error{
            case .DATAERROR:
                self.addEmptyView("数据异常")
                QWTextonlyHud("数据异常", target: self.view)
                break
            case .HTTPERROR:
                self.addEmptyView("网络异常")
                QWTextonlyHud("网络异常", target: self.view)
                break
            case .DATAFAIL:
                self.addEmptyView("当月没有统计数据")
                break
            case .StateFail(let obj):
                guard let data = obj as? [String:Any] else{
                    self.addEmptyView("数据异常")
                    return
                }
                self.addEmptyView(data["Msg"] as? String ?? "")
                break
            }
        }
    }
    
    
    func addEmptyView(_ titleStr:String){
        guard let view = emptyview else {
            self.emptyview = EmptyView(frame: CGRect.zero, _title: titleStr, _top: Float(SCREEN_HEIGHT/5))
            self.view.addSubview(self.emptyview!)
            self.emptyview!.snp.updateConstraints({ (maker) in
                maker.top.equalTo(self.totalview.snp.bottom)
                maker.left.equalTo(self.view.snp.left)
                maker.right.equalTo(self.view.snp.right)
                maker.bottom.equalTo(self.view.snp.bottom)
            })
            return
        }
    }
    
    func removeEmpty(){
        self.emptyview?.removeFromSuperview()
        self.emptyview = nil
    }
    
    func getTongJiDetail() {
        var params:[String:Any] = ["month":month!,"constructionProjectID":ProjectId as! String]
        MNetHttp.sharedInstance.postSingle(API_CALL_METHOD, method: .KQTotalDetail, params: &params, type: KaoQingTotalDetail.self, success: { (bean,_) in
            print("\((bean as! KaoQingTotalDetail).State)")
            QWHudDiss(self.view)
            self.removeEmpty()
            self.card1count = (bean as! KaoQingTotalDetail).Result?.TotalLocationExceptionCount ?? 0
            self.card2count = (bean as! KaoQingTotalDetail).Result?.TotalSignedExceptionCount ?? 0
            self.card3count = (bean as! KaoQingTotalDetail).Result?.TotalSignedNonCount ?? 0
            
            self.dwycTxt.text = "\(self.card1count!)条"
            self.chidao.text = "\(self.card2count!)人次"
            self.wkaoqing.text = "\(self.card3count!)人次"
            
        }) { (error) in
            QWHudDiss(self.view)
            switch error{
            case .DATAERROR:
                self.addEmptyView("数据异常")
                QWTextonlyHud("数据异常", target: self.view)
                break
            case .HTTPERROR:
                self.addEmptyView("网络异常")
                QWTextonlyHud("网络异常", target: self.view)
                break
            case .DATAFAIL:
                self.addEmptyView("当月没有统计数据")
                break
            case .StateFail(let obj):
                guard let data = obj as? [String:Any] else{
                    self.addEmptyView("数据异常")
                    return
                }
                self.addEmptyView(data["Msg"] as? String ?? "")
                break
            }
            
        }
        
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

extension KQViewController:PGDatePickerDelegate{
    func datePicker(_ datePicker: PGDatePicker!, didSelectDate dateComponents: DateComponents!) {
        if dateComponents.month! < 10{
            self.month = "\((dateComponents.year)!)-0\((dateComponents.month)!)-01"
        }else{
            self.month = "\((dateComponents.year)!)-\((dateComponents.month)!)-01"
        }
        self.monthlabel.text = self.month?.timeYearAndMonthStyle2()
        
        
        print("\(month)")
        QWTextWithStatusHud("正在载入数据...", target: self.view)
        self.getTongJiDetail()
        
    }
}
